//
//  NRWCarSubscriptionVC.m
//  New_Runway
//
//  Created by NewLife on 2018/3/16.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarSubscriptionVC.h"
#import "NRWCarSubscriptionCell.h"
#import "NRWCarSubscriptionHeaderCell.h"
#import "SubscriptionFlowLayout.h"
#import "CarInputChooseBrandVC.h"
#import "NRWCarMultipleChoiceVC.h"
#import "PickCityView.h"
#import "NRWCarSelectTemplateModel.h"
#import "CarInputChooseModel.h"

@interface NRWCarSubscriptionVC ()
<UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout,
NRWCarSubscriptionCellDelegate,
NRWCarSubscriptionHeaderCellDelegate,
PickerCityViewDelegate,
NRWCarMultipleChoiceVCDelegate>

@end

@implementation NRWCarSubscriptionVC
{
    UICollectionView *_collectionView;
    NRWCarSelectTemplateModel *model;
    
    NSArray<NRWCarSubSeriesModel *> *seriesModel;
    NSArray<NRWCarSubCityModel *> *cityModel;
    NSArray<NRWCarSubAgeListModel *> *ageModel;
    NSArray<NRWCarSubMileageListModel *> *mileageModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBarView.titleLabel.text = @"车辆订阅";
    
    [self setupUI];
    
    [self loadCarSelectTemplateListData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observerAction:) name:@"ChooseCar" object:nil];
}

- (void)rightItemClick {
    
    seriesModel = @[];
    cityModel = @[];
    ageModel = @[];
    mileageModel = @[];
    
    [_collectionView reloadData];
}

- (void)setupUI {
    
    SubscriptionFlowLayout *flow = [[SubscriptionFlowLayout alloc] init];
    flow.minimumLineSpacing = 9;
    flow.minimumInteritemSpacing = 14.5;
    
    _collectionView = DPCollectionView(flow)
    .setDelegate(self)
    .setDataSource(self)
    .registerHeaderSection(NRWCarSubscriptionHeaderCell.class, @"header")
    .registerFooterSection(UICollectionReusableView.class, @"footer")
    .registerCell(NRWCarSubscriptionCell.class, @"cell")
    .setShowsVerticalScrollIndicator(NO)
    .setShowsHorizontalScrollIndicator(NO)
    .setBackgroundColor([UIColor whiteColor])
    .setFrame(CGRectMake(0, self.navH, Screen_width, Screen_height - self.navH));
    
    self.view.addSubview(_collectionView);
}

- (void)loadCarSelectTemplateListData {
    
    [SVProgressHUD show];
    
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,getCarSelectTemplateList] refreshRequest:NO cache:NO params:@{@"marketId": [NRWCarUser sharedUser].marketId, @"shopId": [NRWCarUser sharedUser].shopId} progressBlock:nil successBlock:^(id response) {
        
        [SVProgressHUD dismiss];
        
        model = [NRWCarSelectTemplateModel mj_objectWithKeyValues:response];
        
        if (model.code == 1) {
            
            seriesModel = model.result.series;
            cityModel = model.result.city;
            ageModel = model.result.carAge;
            mileageModel = model.result.carMileage;
            
            [_collectionView reloadData];
        } else {
            
            [SVProgressHUD showErrorWithStatus:model.msg dismissDelay:1];
        }
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [SVProgressHUD dismiss];
    }];
}

#pragma mark - UICollectionViewDelegate && UICollectionDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 4;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (section == 0) {
        return seriesModel.count;
    } else if (section == 1) {
        return cityModel.count;
    } else if (section == 2) {
        return ageModel.count;
    } else if (section == 3) {
        return mileageModel.count;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NRWCarSubscriptionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.delegate = self;
    
    cell.titleStr = [self returnCellTitleStringWithIndexPath:indexPath];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGSize baseSize = [@"宝马" sizeWithFont:kPingFangRegular13() andMaxSize:CGSizeMake(100, 100)];//算出两个文字的基本长度
    
    CGSize size = [[self returnCellTitleStringWithIndexPath:indexPath] sizeWithFont:kPingFangRegular13() andMaxSize:CGSizeMake(1000, 100)];
    
    if (size.width <= baseSize.width) {
        return CGSizeMake(size.width + 48, size.height + 18);
    } else {
        
        CGFloat width = 25.0 / size.width * 24.0;
        
        if (width < 4.5) {
            return CGSizeMake(size.width + 13, size.height + 18);
        } else if (width > 24) {
            return CGSizeMake(size.width + 48, size.height + 18);
        } else {
            return CGSizeMake(size.width + width * 2, size.height + 18);
        }
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    return UIEdgeInsetsMake(5, 15.5, 17, 15.5);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if (kind == UICollectionElementKindSectionHeader) {
        
        NRWCarSubscriptionHeaderCell *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        
        header.titleStr = [self getHeaderTitleArr][indexPath.section];
        
        header.delegate = self;
        
        return header;
    } else {
        
        if (indexPath.section < 3) {
            return nil;
        }
        
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath] ;
        
        UIView *lineView = DPView()
        .setBackgroundColor(getColorFromString(@"e1e1e1"));
        
        UILabel *label = DPLabel()
        .setFont(kPingFangRegular12())
        .setTextColor(getColorFromString(@"3186dc"))
        .setText(@"注: 所有订阅车源将会显示在首页订阅车源的位置");
        
        UIButton *btn = DPButton()
        .setTitleFont(kPingFangRegular17())
        .setNormalTitleColor(getColorFromString(@"ffffff"))
        .addClickAction(self, @selector(subscribeBtnDidClick:))
        .setNormalTitle(@"订  阅");
        [btn setBackgroundImage:getImageFromName(@"btn_orange_select") forState:UIControlStateNormal];
        
        footer.addSubview(lineView).addSubview(label).addSubview(btn);
        
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(footer);
            make.height.equalTo(@0.5);
        }];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lineView.mas_top).offset(9);
            make.left.equalTo(footer.mas_left).offset(16);
            make.right.equalTo(footer.mas_right).offset(-5);
        }];
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(footer.mas_left).offset(27.5);
            make.right.equalTo(footer.mas_right).offset(-27.5);
            make.height.equalTo(@40);
            make.top.equalTo(label.mas_bottom).offset(47.5);
        }];
        return footer;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    return CGSizeMake(Screen_width, 40);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    
    if (section < 3) {
        return CGSizeZero;
    }
    
    return CGSizeMake(Screen_width, 110);
}

- (NSArray<NSString *>*)getHeaderTitleArr {
    
    return @[@"选择品牌车系", @"选择城市", @"车龄区间", @"里程区间"];
}

#pragma mark - 删除按钮代理
- (void)subscriptionCell:(NRWCarSubscriptionCell *)cell deleteBtnDidClick:(UITapGestureRecognizer *)sender {
    
    NSIndexPath *indexPath = [_collectionView indexPathForCell:cell];
    NSMutableArray *arrM = nil;
    switch (indexPath.section) {
        case 0:
            arrM = seriesModel.mutableCopy;
            [arrM removeObjectAtIndex:indexPath.item];
            seriesModel = arrM.copy;
            break;
        case 1:
            arrM = cityModel.mutableCopy;
            [arrM removeObjectAtIndex:indexPath.item];
            cityModel = arrM.copy;
            break;
        case 2:
            arrM = ageModel.mutableCopy;
            [arrM removeObjectAtIndex:indexPath.item];
            ageModel = arrM.copy;
            break;
        case 3:
            arrM = mileageModel.mutableCopy;
            [arrM removeObjectAtIndex:indexPath.item];
            mileageModel = arrM.copy;
            break;
        default:
            break;
    }
    
    [_collectionView reloadData];
}

#pragma mark - CollectionView组头代理
- (void)subscriptionHeaderCell:(NRWCarSubscriptionHeaderCell *)headerCell didClickWithTitle:(NSString *)title {
    
    if ([title isEqualToString:[self getHeaderTitleArr][0]]) {
        
        CarInputChooseBrandVC *vc = [[CarInputChooseBrandVC alloc] init];
        vc.fromControllerClass = self.class;
        [self.navigationController pushViewController:vc animated:YES];
    } else if ([title isEqualToString:[self getHeaderTitleArr][1]]) {
        
        PickCityView *view = [[PickCityView alloc] init];
        view.delegate = self;
        view.pickerViewHeight = 300;
        [view show];
    } else if ([title isEqualToString:[self getHeaderTitleArr][2]]) {
        
        NSMutableArray *arrM = [NSMutableArray array];
        for (NRWCarSubAgeListModel *itemModel in ageModel) {
            [arrM addObject:itemModel.carAgeId];
        }
        
        NRWCarMultipleChoiceVC *vc = [[NRWCarMultipleChoiceVC alloc] init];
        vc.type = NRWCarMultipleChoiceVCTypeAgeList;
        vc.fromClass = self.class;
        vc.delegate = self;
        vc.selectAgeIdArr = arrM.copy;
        [self.navigationController pushViewController:vc animated:YES];
    } else if ([title isEqualToString:[self getHeaderTitleArr][3]]) {
        
        NSMutableArray *arrM = [NSMutableArray array];
        for (NRWCarSubMileageListModel *itemModel in mileageModel) {
            [arrM addObject:itemModel.carMileageId];
        }
        
        NRWCarMultipleChoiceVC *vc = [[NRWCarMultipleChoiceVC alloc] init];
        vc.type = NRWCarMultipleChoiceVCTypeMileageList;
        vc.fromClass = self.class;
        vc.delegate = self;
        vc.selectMileageIdArr = arrM.copy;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - 选择省市代理
- (void)pickerArea:(PickCityView *)pickerArea selectProvince:(NSString *)province selectCity:(NSString *)city selectProvinceId:(NSString *)provinceId selectCityId:(NSString *)cityId {
    
    for (NRWCarSubCityModel *itemModel in cityModel) {
        if ([itemModel.cityId isEqualToString:cityId]) {
            [SVProgressHUD showErrorWithStatus:@"请不要重复选择" dismissDelay:1];
            return;
        }
    }
    
    NSMutableArray *arrM = [NSMutableArray arrayWithArray:cityModel];
    
    NRWCarSubCityModel *model = [[NRWCarSubCityModel alloc] init];
    model.cityId = cityId;
    model.cityName = city;
    
    [arrM addObject:model];
    
    cityModel = arrM.copy;
    
    [_collectionView reloadData];
}

#pragma mark - 车龄代理 && 历程代理
- (void)multipleChoiceVC:(NRWCarMultipleChoiceVC *)vc ChoiceCompleted:(NSArray *)arr {
    
    if (vc.type == NRWCarMultipleChoiceVCTypeAgeList) {
        
        ageModel = arr;
    } else if (vc.type == NRWCarMultipleChoiceVCTypeMileageList) {
        
        mileageModel = arr;
    }
    [_collectionView reloadData];
}

#pragma mark - touchAction
- (void)subscribeBtnDidClick:(UIButton *)sender {
    
    [SVProgressHUD show];
    
    NSMutableDictionary *templateJson = [NSMutableDictionary dictionary];
    if (seriesModel.count > 0) {
        NSMutableArray *arrM = [NSMutableArray array];
        for (NRWCarSubSeriesModel *itemModel in seriesModel) {
            [arrM addObject:[itemModel mj_JSONObject]];
        }
        [templateJson setObject:arrM.copy forKey:@"series"];
    }
    if (cityModel.count > 0) {
        NSMutableArray *arrM = [NSMutableArray array];
        for (NRWCarSubCityModel *itemModel in cityModel) {
            [arrM addObject:[itemModel mj_JSONObject]];
        }
        [templateJson setObject:arrM.copy forKey:@"city"];
    }
    if (ageModel.count > 0) {
        NSMutableArray *arrM = [NSMutableArray array];
        for (NRWCarSubAgeListModel *itemModel in ageModel) {
            [arrM addObject:[itemModel mj_JSONObject]];
        }
        [templateJson setObject:arrM.copy forKey:@"carAge"];
    }
    if (mileageModel.count > 0) {
        NSMutableArray *arrM = [NSMutableArray array];
        for (NRWCarSubMileageListModel *itemModel in mileageModel) {
            [arrM addObject:[itemModel mj_JSONObject]];
        }
        [templateJson setObject:arrM.copy forKey:@"carMileage"];
    }
    
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    [dictM setObject:[NRWCarUser sharedUser].marketId forKey:@"marketId"];
    [dictM setObject:[NRWCarUser sharedUser].shopId forKey:@"shopId"];
    [dictM setObject:[templateJson mj_JSONString] forKey:@"templateJson"];
    [dictM setObject:[NRWCarUser sharedUser].userId forKey:@"userId"];
    
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api, insertCarSelectTemplate] refreshRequest:NO cache:NO params:dictM.copy progressBlock:nil successBlock:^(id response) {
        
        [SVProgressHUD dismiss];
        
        if ([response[@"code"] integerValue] == 1) {
            
            [SVProgressHUD showSuccessWithStatus:@"订阅成功" dismissDelay:1 didDismiss:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        } else {
            
            [SVProgressHUD showErrorWithStatus:response[@"msg"] dismissDelay:1];
        }

    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [SVProgressHUD dismiss];
    }];
}

#pragma mark - observerAction
#pragma mark 选择车系通知
- (void)observerAction:(NSNotification *)notification {
    
    CarInputChooseModel *carModel = notification.object;
    
    for (NRWCarSubSeriesModel *itemModel in seriesModel) {
        if ([itemModel.seriesId isEqualToString:[NSString stringWithFormat:@"%zd",carModel.seriesId]]) {
            [SVProgressHUD showErrorWithStatus:@"请不要重复选择" dismissDelay:1];
            return;
        }
    }
    
    NSMutableArray *arrM = [NSMutableArray arrayWithArray:seriesModel];
    
    NRWCarSubSeriesModel *serModel = [[NRWCarSubSeriesModel alloc] init];
    serModel.seriesId = [NSString stringWithFormat:@"%zd", carModel.seriesId];
    serModel.seriesName = [NSString stringWithFormat:@"%@ %@", carModel.brandName, carModel.seriesName];
    [arrM addObject:serModel];
    
    seriesModel = arrM.copy;
    
    [_collectionView reloadData];
}

#pragma mark - privateMothed
#pragma mark 获取对应cell的title
- (NSString *)returnCellTitleStringWithIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        return seriesModel[indexPath.row].seriesName;
    } else if (indexPath.section == 1) {
        
        return cityModel[indexPath.row].cityName;
    } else if (indexPath.section == 2) {
        
        return ageModel[indexPath.row].carAgeRemark;
    } else if (indexPath.section == 3) {
        
        return mileageModel[indexPath.row].carMileageRemark;
    }
    return nil;
}

@end
